﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.Progression;
using ReflectionMagic;
using Microsoft.VisualStudio.Diagrams.View;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows;

namespace Timtopia.DGMLPosterView
{
    public class ModularGraphGenerationController : GraphGenerationController
    {
        protected Graph _graph;

        protected ModularGraphGenerationController(IServiceProvider sp, Func<Graph> generate) 
            : base(sp) 
        {
            this.generate = generate;
        }

        Func<Graph> generate;

        public static void CreateGraph(IServiceProvider sp, Func<Graph> generate)
        {
            var gen = new ModularGraphGenerationController(sp, generate);
            gen.Start();
        }

        protected override void Initialize()
        {
            this.AddDocumentCreationStep("Modular Graph");
            this.AddProgressStep(ac =>
            {
                _graph = generate();
                return true;
            }, "Generating Graph", false);
            this.AddProgressStep(ac =>
            {
                using (var scope = new GraphTransactionScope())
                {
                    this.Window.Graph = _graph;
                    scope.Complete();
                }
                return true;
            }, "Displaying graph", true);
        }

        private string progressTitle = "Generating Graph";
        protected override string ProgressTitle
        {
            get
            {
                return progressTitle;
            }
            set
            {
                progressTitle = value;
            }
        }

        protected override void OnDocumentCreated(string filename)
        {
            base.OnDocumentCreated(filename);

            SetCustomVisualFactory(this.Window);
        }

        public static void SetCustomVisualFactory(IGraphDocumentWindowPane window)
        {
            dynamic pane = window.AsDynamic();
            GraphControl gc = (GraphControl)pane.GraphControl;
            gc.Diagram.Canvas.VisualFactory = new PosterViewVisualFactory(gc);

            foreach (var graphObject in window.Graph.Nodes)
            {
                ISpatialItem spatialItem = gc.Diagram.GetSpatialItem(graphObject);
                gc.Diagram.Canvas.ForceVirtualizeItem(spatialItem);
                gc.Diagram.UpdateRealization();
            }
        }
    }
}

